/**
 * 
 */
package com.shy.freemarker.exception;

import java.io.IOException;
import java.io.Writer;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import freemarker.core.Environment;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

/**
 * <p>Title:FreemarkerExceptionHandler
 * <p>Description: 模板錯誤异常处理，正常渲染文件，將錯誤提示输出
 * @author H2013788
 * @date 2019年9月11日
 */
public class FreemarkerExceptionHandler implements TemplateExceptionHandler {
	
	/**
     * log
     */
	private Logger logger = LogManager.getLogger(this.getClass());

	@Override
    public void handleTemplateException(TemplateException te, Environment env, Writer out) throws TemplateException {
			logger.warn("[Freemarker Error: " + te.getMessage() + "]");
	        String missingVariable = "undefined";
	        try {
	            String[] tmp = te.getMessageWithoutStackTop().split("\n");
	            if(tmp.length > 0) {
	            	for (String msg : tmp) {
						if(msg.startsWith("==>")) {
							missingVariable = msg;
						}
					}
	            }
	            out.write("[模板表達式錯誤]");
	            logger.error("[模板出错:" + missingVariable + "]", te);
	        } catch (IOException e) {
	            throw new TemplateException(
	                    "Failed to print error message. Cause: " + e, env);
	        }
    }

}
